<template>
  <section class="card">
    <header class="card-header">
      <div class="title">试卷管理</div>
      <div class="ops">
        <el-input v-model="query.keyword" placeholder="按名称搜索" size="small" style="width: 220px" @keyup.enter="loadList" />
        <el-button size="small" @click="loadList">查询</el-button>
        <el-button size="small" class="secondary" @click="resetQuery">重置</el-button>
        <el-button size="small" type="primary" @click="openCreate">创建试卷</el-button>
      </div>
    </header>
    <div class="card-body">
      <el-table :data="list" border stripe v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="试卷名称" min-width="180" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="durationMinutes" label="时长(分钟)" width="120" />
        <el-table-column prop="totalScore" label="总分" width="80" />
        <el-table-column prop="passScore" label="及格线" width="80" />
        <el-table-column prop="randomizeQuestions" label="乱序题目" width="100">
          <template #default="{ row }">
            <el-tag :type="row.randomizeQuestions ? 'success' : 'info'">{{ row.randomizeQuestions ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
      <el-table-column prop="randomizeOptions" label="乱序选项" width="100">
          <template #default="{ row }">
            <el-tag :type="row.randomizeOptions ? 'success' : 'info'">{{ row.randomizeOptions ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="开启考试" width="120">
          <template #default="{ row }">
            <el-switch
              :model-value="row.status === 1 ? 1 : 0"
              :active-value="1"
              :inactive-value="0"
              @change="(val) => toggleStatus(row, val)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="openEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="remove(row)">删除</el-button>
            <el-button size="small" @click="viewQuestions(row)">查看题目</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="query.size"
          :current-page="query.page"
          :total="total"
          @current-change="handlePage"
        />
      </div>
    </div>

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="520px" align-center>
      <el-form :model="form" label-width="100px">
        <el-form-item label="试卷名称">
          <el-input v-model="form.name" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="时长(分钟)">
          <el-input-number v-model="form.durationMinutes" :min="0" :max="600" />
        </el-form-item>
        <el-form-item label="总分">
          <el-input-number v-model="form.totalScore" :min="0" :max="1000" />
        </el-form-item>
        <el-form-item label="及格线">
          <el-input-number v-model="form.passScore" :min="0" :max="1000" />
        </el-form-item>
        <el-form-item label="乱序题目">
          <el-switch v-model="form.randomizeQuestions" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="乱序选项">
          <el-switch v-model="form.randomizeOptions" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </section>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { pagePapers, createPaper, updatePaper, deletePaper } from '@/api/exam/exam'
import { useRouter } from 'vue-router'

const router = useRouter()

const list = ref<any[]>([])
const loading = ref(false)
const total = ref(0)
const query = reactive({ keyword: '', page: 1, size: 10 })

async function loadList() {
  loading.value = true
  try {
    const res = await pagePapers({ keyword: query.keyword, page: query.page, size: query.size })
    const raw = res?.data?.data ?? res?.data
    if (Array.isArray(raw)) {
      list.value = raw
      total.value = raw.length
    } else {
      list.value = raw?.list ?? []
      total.value = raw?.total ?? 0
      // 适配后端返回的页码
      if (raw?.pageNum != null || raw?.page != null) query.page = raw.pageNum ?? raw.page
      if (raw?.pageSize != null || raw?.size != null) query.size = raw.pageSize ?? raw.size
    }
  } catch (e) {
    ElMessage.error('加载试卷失败')
  } finally {
    loading.value = false
  }
}

function resetQuery() {
  query.keyword = ''
  query.page = 1
  loadList()
}

function handlePage(p: number) {
  query.page = p
  loadList()
}

// 创建/编辑
const dialogVisible = ref(false)
const dialogTitle = ref('创建试卷')
const form = reactive({
  id: undefined as number | undefined,
  name: '',
  description: '',
  durationMinutes: 60,
  totalScore: 100,
  passScore: 60,
  randomizeQuestions: 1 as number | 0 | 1,
  randomizeOptions: 0 as number | 0 | 1,
})

function openCreate() {
  dialogTitle.value = '创建试卷'
  form.id = undefined
  form.name = ''
  form.description = ''
  form.durationMinutes = 60
  form.totalScore = 100
  form.passScore = 60
  form.randomizeQuestions = 1
  form.randomizeOptions = 0
  dialogVisible.value = true
}

function openEdit(row: any) {
  dialogTitle.value = '编辑试卷'
  form.id = row.id
  form.name = row.name
  form.description = row.description
  form.durationMinutes = row.durationMinutes
  form.totalScore = row.totalScore
  form.passScore = row.passScore
  form.randomizeQuestions = row.randomizeQuestions ? 1 : 0
  form.randomizeOptions = row.randomizeOptions ? 1 : 0
  dialogVisible.value = true
}

async function submit() {
  try {
    if (form.id) {
      await updatePaper(form.id, {
        name: form.name,
        description: form.description,
        durationMinutes: form.durationMinutes,
        totalScore: form.totalScore,
        passScore: form.passScore,
        randomizeQuestions: form.randomizeQuestions,
        randomizeOptions: form.randomizeOptions,
      })
      ElMessage.success('试卷更新成功')
    } else {
      await createPaper({
        name: form.name,
        description: form.description,
        durationMinutes: form.durationMinutes,
        totalScore: form.totalScore,
        passScore: form.passScore,
        randomizeQuestions: form.randomizeQuestions,
        randomizeOptions: form.randomizeOptions,
      })
      ElMessage.success('试卷创建成功')
    }
    dialogVisible.value = false
    loadList()
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

function remove(row: any) {
  ElMessageBox.confirm(`确认删除试卷【${row.name}】吗？该操作不可恢复。`, '提示', { type: 'warning' })
    .then(async () => {
      try {
        await deletePaper(row.id)
        ElMessage.success('删除成功')
        loadList()
      } catch (e) {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

function viewQuestions(row: any) {
  router.push(`/examPaper/${row.id}`)
}

onMounted(loadList)

// 开启/关闭考试（更新 status 字段：1=开启，0/空=未开启）
async function toggleStatus(row: any, val: number) {
  const prev = row.status
  // 乐观更新
  row.status = val
  try {
    await updatePaper(row.id, { status: val } as any)
    ElMessage.success(val === 1 ? '已开启考试' : '已关闭考试')
  } catch (e) {
    // 失败回滚
    row.status = prev
    ElMessage.error('更新考试状态失败')
  }
}
</script>

<style scoped>
.card-header { display: flex; align-items: center; justify-content: space-between; padding: 6px 6px 12px 6px; border-bottom: 1px solid #f0f0f0; }
.card-header .title { font-weight: 600; }
.card-header .ops { display: flex; gap: 8px; align-items: center; }
.card-body { padding-top: 12px; }
.pager { display: flex; justify-content: flex-end; margin-top: 10px; }
.dialog-footer { display: flex; gap: 8px; justify-content: flex-end; }
</style>